<template>
    <div>
        <!-- 角色管理 -->
        <el-form v-if="showSearch" :model="params">
            <el-row :gutter="24">
                <el-col :span="6">
                    <el-form-item label="角色名称" :class="{ 'bold-label': true }">
                        <el-input v-model="params.roleName" placeholder="请输入角色名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="权限字符" :class="{ 'bold-label': true }">
                        <el-input v-model="params.roleKey" placeholder="请输入角色名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态" :class="{ 'bold-label': true }">
                        <el-select clearable v-model="params.status" placeholder="角色状态">
                            <el-option label="正常" value="0" />
                            <el-option label="停用" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="创建时间" :class="{ 'bold-label': true }">
                        <el-date-picker v-model="createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                            start-placeholder="开始时间" end-placeholder="结束时间" :default-time="defaultTime"
                            @change="handleDateChange" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" plain @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click=handleaddw>新增</el-button>
                    <el-button type="success" plain :disabled="isSingleRowSelected" :icon="EditPen"
                        @click="handleupdateId">修改</el-button>
                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDeleteIds">删除</el-button>
                    <el-button type="warning" plain :icon="Download">导出</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearch" />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="Reload" />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 表格部分 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="roleId" label="角色编号" />
                <el-table-column prop="roleName" label="角色名称" />
                <el-table-column prop="roleKey" label="权限字符" />
                <el-table-column prop="roleSort" label="显示排序" align="center" />
                <el-table-column prop="status" label="状态" align="center">
                    <!-- status 为'0'表示正常，1表示停用 -->
                    <!-- @change：事件处理器 handleSatausChange来处理状态变化 -->
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" :active-value="'0'" :inactive-value="'1'"
                            @change="handleSatausChange(scope.row.status, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" />
                <el-table-column width="270px" label="操作" align="center">
                    <template #default="scope">
                        <el-button plain type="primary" text size="small" :icon="EditPen"
                            @click="handleupdate(scope.$index, scope.row)">修改</el-button>
                        <el-button plain type="primary" text size="small" :icon="Delete"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        <!--<el-button plain type="primary" text size="small" :icon="Plus"
                            @click="handleadd(scope.$index, scope.row)">分配用户</el-button>-->
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :page-sizes="pageSizes" layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <!-- 添加弹窗显示 -->
        <addDialog :addDialog="dialogVisibleAdd" :treeData="treeData" @close-dialog="colseDialog" />
        <!-- 修改弹窗显示 -->
        <UpdateDialog :updateDialog="dialogVisibleUpdate" :rolesUpdate="rolesUpdate" :treeData="treeData"
            @close-dialog="colseDialog" />

    </div>
</template>

<script setup>
import addDialog from '@/components/RoleManagement/addDialog.vue';
import UpdateDialog from '@/components/RoleManagement/UpdateDialog.vue';
import { deleteRoleIds, findRoleList, findMenuList, updateRoleStatus, findRoleAssignUsers } from '@/apis/lth/index';
import { nextTick, onMounted, ref, reactive } from 'vue';
import { Search, Refresh, Delete, Download, Plus, EditPen } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// import router from '@/router';
// import { useLayoutStore } from '@/stores/settings'
const tableData = ref([]);  // 表格数据
const pageResult = ref({}); // 分页数据
let ids = ref([]); // 选中行的id数组
let roleVal = ref([]); //选中行
const deleteDisabled = ref(true); // 删除按钮禁用状态,默认禁用
const isSingleRowSelected = ref(true); // 修改按钮禁用状态,默认禁用
const dialogVisibleAdd = ref(false); // 添加弹窗显示
const dialogVisibleUpdate = ref(false); // 修改弹窗显示
const treeData = ref([]); //菜单列表
let now = new Date();
let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);//开始时间默认为 00:00:00
let endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);//结束时间默认为 23:59:59
let defaultTime = ref([startOfDay, endOfDay]);//默认日期时间
const rolesUpdate = ref({});//修改参数据条
// const settingStore = useLayoutStore()
// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 10,
    roleName: '',
    roleKey: '',
    status: '',
    startCreateTime: '',
    endCreateTime: '',
})
const createTime = ref([]);//时间框存储

onMounted(async () => {
    // 加载角色列表数据
    pageResult.value = await findRoleList(params.value)
    tableData.value = pageResult.value.records || []
    if (!pageResult.value.total) {
        pageResult.value.total = 0
    }
})

//弹窗时查询的菜单列表
onMounted(async () => {
    treeData.value = await findMenuList()
})

//刷新
const loadRoleList = async () => {
    pageResult.value = await findRoleList(params.value)
    tableData.value = pageResult.value.records || []
    if (!pageResult.value.total) {
        pageResult.value.total = 0
    }
}
// handleDateChange：通常用于处理日期选择器（如 el-date-picker）的值变化事件。
const handleDateChange = (value) => {
    if (value) {
        params.value.startCreateTime = value[0];
        params.value.endCreateTime = value[1];
    } else {
        params.value.startCreateTime = null;
        params.value.endCreateTime = null;
    }
}
// 处理搜索
const handleSearch = async () => {
    await loadRoleList()
}

// 处理重置
const handleReset = async () => {
    //重置搜索参数
    params.value = {}
    //重置时间参数
    createTime.value = []
    await loadRoleList()
}

//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新
const Reload = async () => {
    await loadRoleList()
}

// 分页大小
const pageSizes = [10, 20, 30, 40, 50]
/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    await loadRoleList()
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    await loadRoleList()
}
/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return row.roleKey !== 'admin';
}
/**
 * 处理选中行变化
 * @param val 选中行的数组
 */
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.roleId) // 使用map方法过滤出选中行的roleId数组
    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        rolesUpdate.value = { ...val[0] };//把选中的这条数据添加给修改数据（rolesUpdate）
    }
}
/**
 * 处理删除选中行
 * @param ids 选中行的id数组
 */
const handleDeleteIds = () => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let shouldContinue = true;
        for (let i = 0; i < ids.value.length && shouldContinue; i++) {
            const id = ids.value[i];
            const count = await findRoleAssignUsers([id]);
            if (count > 0) {
                // 找到已分配的角色
                const role = roleVal.value.find(item => item.roleId === id);
                if (role) {
                    ElMessage.error(`${role.roleName}已分配，不能删除`);
                    shouldContinue = false; // 停止进一步的删除操作
                    break;//结束循环
                }
            }
        }
        if (shouldContinue) {
            // 如果没有已分配的角色，执行删除操作
            await deleteRoleIds(ids.value);
            await loadRoleList();
            ElMessage.success("删除成功");
            // 重新加载选中状态
            const selectedRoles = roleVal.value.filter(item => ids.value.includes(item.roleId));
            ids.value = selectedRoles.map(item => item.roleId);
        }
    })
}
/**
 * 删除角色（根据id）
 * @param index 行索引
 * @param row 行数据
 */
const handleDelete = async (index, row) => {
    ids.value.length = 0;
    ids.value.push(row.roleId);
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (row.roleKey === "admin") {
            ElMessage.error(`不允许操作超级管理员角色`);
            return;
        }
        const count = await findRoleAssignUsers(ids.value);
        if (count > 0) {
            ElMessage.error(`${row.roleName}已分配，不能删除`);
            ids.value = [];
            return;
        }
        await deleteRoleIds(ids.value);
        await loadRoleList();
        ElMessage.success("删除成功");
    })
}

//修改角色状态
let handleSatausChange = async (val, row) => {
    if (row.roleKey === "admin") {
        ElMessage.error(`不允许操作超级管理员角色`);
        row.status = row.status == "0" ? "1" : "0"
        return;
    }
    if (!row) {
        ElMessage.error('无效的角色信息')
        return;
    }
    ElMessageBox.confirm(
        `确认要${val === "0" ? '"启用"' : '"停用"'}"${row.roleName}"角色吗？`,
        '系统提示',
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: 'warning'
        }
    ).then(async () => {
        const data = {
            roleId: row.roleId,
            status: val
        }
        await updateRoleStatus(data)
        loadRoleList();
    }).catch(() => {
        row.status = row.status == "0" ? "1" : "0"
    })

}

//新增角色，弹窗显示
const handleaddw = () => {
    dialogVisibleAdd.value = true;
}
//修改角色，弹窗显示
const handleupdate = (index, row) => {
    dialogVisibleUpdate.value = true;
    Object.assign(rolesUpdate.value, row)
}
//handleupdateId:修改角色
const handleupdateId = () => {
    dialogVisibleUpdate.value = true;
}
// //分配用户
// const handleadd = (index, row) => {
//     console.log(row)
//     if (settingStore.tabs.length <= 0 || !settingStore.tabs.some(item => item.name == '/manage/organizationalStructure/roleManagement/AssignUsers')) {
//         settingStore.tabs.push({
//             name: '/manage/organizationalStructure/roleManagement/AssignUsers',
//             label: '分配用户',
//         })
//     }
//     settingStore.menuActive.name = '/manage/organizationalStructure/roleManagement/AssignUsers'
//     router.push("/manage/organizationalStructure/roleManagement/AssignUsers")
// }

//关闭弹窗
const colseDialog = async () => {
    dialogVisibleAdd.value = false
    dialogVisibleUpdate.value = false
    await loadRoleList();
}

</script>

<style scoped>
::v-deep .dialogs {
    padding: 30px 20px
}

.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}

/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep.el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}
</style>
